/**
 * Copyright 2009, 2009 Srikalyan Chandrashekar
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.

 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
**/

import java.util.*;

/** This class can be used to create a thread pool. The default pool size has 
 * been set to 2. This can be changed programatically by passing the value
 * through the constructor. Usage :
 * 1) Create Thread pool object and appropriately set the pool size.
 * 2) add threads to the pool 
 * 3) kickStart and thats it the , pool takes care of launching and managing the 
 *    threads. 
 * @author srikalyc (srikalyan.chandrashekar@gmail.com)
 *
 */
public class ThreadPool implements Runnable {
  public static int POOL_SIZE = 2;// Default pool size
  public static int POOL_STATUS_CHECK_TIME = 1000;//In milli seconds
  private List<Runnable> threadsInPool;
  private Thread self;
  
  public ThreadPool() {
    threadsInPool = new ArrayList<Runnable>();
  }

  public ThreadPool(int size) {
    threadsInPool = new ArrayList<Runnable>();
    POOL_SIZE = size;
  }

  public void addThreadToPool(Runnable th) {
    threadsInPool.add(th);
  }

  public void kickStart() {
    self = new Thread(this);
    self.start();
  }

  public void run() {
    Thread thArr[] = new Thread[POOL_SIZE];
    while (true) {
      if (threadsInPool.isEmpty()) {// We are done
        for (int i = 0; i < POOL_SIZE; i++) {
          if (thArr[i] != null) {
            i = 0;
            pausePool();
          }
        }
        break;
      }
      for (int i = 0; i < POOL_SIZE; i++) {//Check if appropriate number of threads are alive in pool
        if (thArr[i] == null || !thArr[i].isAlive()) {//If no then spin off new threads.
          if (!threadsInPool.isEmpty()) {
            thArr[i] = new Thread(threadsInPool.remove(0));
            thArr[i].start();
          }
        }
      }
      pausePool();
    }
  }
  /**
   * This method can be called from outside the pool to check if pool thread is
   * alive or not. 
   * @return
   */
  
  public boolean isPoolAlive() {
     if (self.isAlive())
       return true;
     return false;
  }
  
  private void pausePool() {
    try {
      Thread.sleep(POOL_STATUS_CHECK_TIME);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}
